package com.david.files.controller;

import com.david.common.utils.MinioUtils;
import com.david.files.pojo.Entity.FileEntity;
import com.david.files.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

import static com.david.common.utils.ResultUtils.success;

@RestController
@RequestMapping("/equipment/file")
@Slf4j
public class FileController {
    @Autowired
    private MinioUtils minioUtils;
    @Autowired
    private FileService fileService;

    /**
    * @Description: 上传文档
    * @Param: [files, bucketName, appName, category]
    * @return: org.springframework.http.ResponseEntity<java.lang.Object>
    * @Author: david
    * @Date: 2024/7/11
    */
    @PostMapping("/upload")
    public ResponseEntity<Object> upload(@RequestParam("multipartFile") MultipartFile[] files,
                                         @RequestParam("bucketName") String bucketName,
                                         @RequestParam("appName") String appName,
                                         @RequestParam("category") String category){

        log.info("上传文件:{}",files.length);
        for(MultipartFile file : files) {
            String url = minioUtils.upload(file,bucketName);
            FileEntity uploadEntity = FileEntity.builder()
                    .name(file.getOriginalFilename().split("\\.")[0])
                    .appName(appName)
                    .category(category)
                    .fileType(file.getContentType())
                    .url(url)
                    .build();
            fileService.upload(uploadEntity);
        }
        return success(true, "上传成功");
    }

    /**
    * @Description: 获取相应条件下的文档列表
    * @Param: [fileType, appName, category]
    * @return: org.springframework.http.ResponseEntity<java.lang.Object>
    * @Author: david
    * @Date: 2024/7/11
    */
    @GetMapping("/list")
    public ResponseEntity<Object> list(@RequestParam("fileType") String fileType,
                                       @RequestParam("appName") String appName,
                                       @RequestParam("category") String category) {
        log.info("获取{}应用{}分类的文档列表",appName,category);
        FileEntity file = FileEntity.builder().appName(appName).category(category).fileType(fileType).build();
        List<FileEntity> fileList = fileService.getList(file);
        System.out.println(fileList);
        return success(true,fileList);
    }

    @DeleteMapping("/del/{id}")
    public ResponseEntity<Object> delDoc(@PathVariable("id") Integer id) {
        log.info("删除文档{}",id);
        fileService.delDoc(id);
        return success(true, "删除成功");
    }

}
